package threadpoolnio.client;

import threadpoolnio.NetPrintStream;
import threadpoolnio.util.Message;
import threadpoolnio.util.Translate;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowListener;
import java.io.File;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class ClientUI3 {
    public JTextArea txtAccept;
    public JPanel mainpanel;
    public JList userlist;
    private JButton btnSendFile;
    private JButton btnSendMsg;
    private JButton btnSend;
    private JTextArea txtSend;
    private NIOClient client = null;
    private static JFrame frame = null;

    private DatagramSocket clientSocket;
    private Message msg;
    private byte[] data = new byte[8096];

    public void connectServer() {
        if (client == null) {
            NetPrintStream printStream = new NetPrintStream(System.out, txtAccept);
            System.setErr(printStream);
            System.setOut(printStream);
            String ip = msg.getToAddr().getHostName();
            int port = msg.getToPort();
            client = new NIOClient(ip, port);
        }
    }

    public ClientUI3(DatagramSocket socket, Message msg) {
        this.clientSocket = socket;
        this.msg = msg;
        //创建客户机消息接收和处理信息
        Thread recvThread = new ReceiveMessage(clientSocket, this);
        recvThread.start();//启动消息线程
        connectServer();


        btnSend.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    msg.setText(txtSend.getText());//获取输入的文本
                    Object sendUser = userlist.getSelectedValue();
                    if (sendUser != null && !sendUser.equals(msg.getUserId())) {
                        msg.setType("M_USER");//设置私聊消息类型
                        msg.setTargetId(sendUser.toString());//发给哪个用户
                    } else{
                        msg.setType("M_MSG");
                    }
                    data = Translate.ObjectToByte(msg);
                    DatagramPacket packet = new DatagramPacket(data, data.length, msg.getToAddr(), msg.getToPort());
                    clientSocket.send(packet);
                    txtSend.setText(" ");
                } catch (IOException ex) {
                    ex.printStackTrace();
                    JOptionPane.showMessageDialog(null, ex.getMessage(), "错误提示", JOptionPane.ERROR_MESSAGE);
                }
            }
        });

        btnSendMsg.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                if (client != null) {
//                    client.sendMsg("0");
                    client.sendMsg(txtSend.getText());
                    txtSend.setText(" ");
                } else
                    JOptionPane.showConfirmDialog(frame, "请先连接服务器", "出错了!", JOptionPane.YES_OPTION);
            }

        });

        btnSendFile.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (client != null) {
                    //文件选择框
                    JFileChooser fileChooser = new JFileChooser();
                    //获取并设置当前的目录为程序运行的目录
                    fileChooser.setCurrentDirectory(new File(System.getProperty("user.dir")));
                    if (fileChooser.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION) {
                        //获取当前选择文件的绝对路径
                        String file = fileChooser.getSelectedFile().getAbsolutePath();
//                        client.sendMsg("1:"+fileChooser.getSelectedFile().getName());
                        client.sendFile(file);
                    }
                } else
                    JOptionPane.showConfirmDialog(frame, "请先连接服务器", "出错了!", JOptionPane.YES_OPTION);
            }
        });

    }


    public WindowListener windowAdapter() {
        return new java.awt.event.WindowAdapter() {
            @Override
            public void windowClosing(java.awt.event.WindowEvent e) {
                try {
                    msg.setType("M-QUIT");//消息类型
                    msg.setText(null);
                    data = Translate.ObjectToByte(msg); //消息对象序列化

                    DatagramPacket packet = new DatagramPacket(data, data.length, msg.getToAddr(), msg.getToPort());
                    clientSocket.send(packet);
                } catch (IOException ex) {
                }
                clientSocket.close(); //关闭套接字
                client.close();

            }


        };
    }

}

